package com.reverie.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reverie.common.pojo.CommonPageReq;
import com.reverie.config.CommonException;
import com.reverie.entity.User;
import com.reverie.mapper.UserMapper;
import com.reverie.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User login(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername,user.getUsername());
        User userByUserName = getOne(wrapper);
        if(userByUserName == null){
            throw new CommonException("登录账号不存在，请确认");
        }

        String realPwd = MD5.create().digestHex(MD5.create().digestHex(user.getPassword()) + userByUserName.getRdmSalt());

        if(!userByUserName.getPassword().equals(realPwd)){
            throw new CommonException("密码错误，请确认");
        }

        return userByUserName;
    }

    @Override
    public User getByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername,username);
        return getOne(wrapper);
    }

    @Override
    public Page<User> getPage(CommonPageReq<User> pageParam) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User userParam = pageParam.getQueryParam();
        if (StringUtils.hasLength(userParam.getUsername())) {
            wrapper.lambda().like(User::getUsername, userParam.getUsername());
        }
        if(userParam.getOrgId() != null){
            wrapper.lambda().eq(User::getOrgId, userParam.getOrgId());
        }
        Object loginId = StpUtil.getLoginId();
        User user = getById(loginId.toString());
        if(user.getRoleId() != 202401){
            wrapper.lambda().eq(User::getCreateUserId, loginId.toString());
        }

        wrapper.orderByDesc("id");
        Page<User> userPage = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        page(userPage, wrapper);
        return userPage;
    }

}
